/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.peer.ui.async.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.JOptionPane;

import org.ourgrid.common.ui.InputFieldsUI;
import org.ourgrid.common.ui.gui.CommuneDetectionDelaySettingsPanel;
import org.ourgrid.common.ui.gui.CommuneSettingsPanel;
import org.ourgrid.peer.ui.async.client.PeerAsyncInitializer;
import org.ourgrid.peer.ui.async.model.PeerAsyncUIModel;

public class PeerConfigurationPanel extends javax.swing.JPanel implements InputFieldsUI {
    
	private static final long serialVersionUID = 1L;
	private PeerAsyncUIModel model;
	private CommuneDetectionDelaySettingsPanel fdPanel;
	private CACertificatePanel cACertificatePanel;
	private VomsAuthPanel vomsAuthPanel;
	private TagsPeerConfigurationPanel tagsPeerConfigurationPanel;
	
	/** Creates new form PeerConfigurationPanel */
    public PeerConfigurationPanel(PeerAsyncUIModel model) {
    	this.model = model;
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     * @param model 
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabs = new javax.swing.JTabbedPane();
        basicSettingsPanel = new javax.swing.JPanel();
        basicPeerConfigurationPanel = new org.ourgrid.peer.ui.async.gui.BasicPeerConfigurationPanel(model);
        discoveryServiceSettingsPanel = new org.ourgrid.peer.ui.async.gui.DiscoveryServiceSettingsPanel(model);
        tagsPeerConfigurationPanel = new TagsPeerConfigurationPanel(model);
        communePanel = new CommuneSettingsPanel(model);
        fdPanel = new CommuneDetectionDelaySettingsPanel(model);
        cACertificatePanel = new CACertificatePanel(model);
        vomsAuthPanel = new VomsAuthPanel(model);
        advancedPeerSettingsPanel = new org.ourgrid.peer.ui.async.gui.AdvancedPeerSettingsPanel(model);
//        try {
//			logSettingsPanel = new org.ourgrid.common.ui.gui.LogSettingsPanel(model, component);
//		} catch (FileNotFoundException e1) {
//			JOptionPane.showMessageDialog(this, "Log properties file was not found, log settings panel will not be available.", "Warning", JOptionPane.WARNING_MESSAGE);
//		} catch (IOException e1) {
//			JOptionPane.showMessageDialog(this, "Error while loading log properties file, log settings panel will not be available.", "Warning", JOptionPane.WARNING_MESSAGE);		
//		}
        restoreDefaultsButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();

        basicPeerConfigurationPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Basic settings"));

        discoveryServiceSettingsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Discovery Service settings"));

        org.jdesktop.layout.GroupLayout basicSettingsPanelLayout = new org.jdesktop.layout.GroupLayout(basicSettingsPanel);
        basicSettingsPanel.setLayout(basicSettingsPanelLayout);
        basicSettingsPanelLayout.setHorizontalGroup(
            basicSettingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(basicSettingsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(basicSettingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, discoveryServiceSettingsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 762, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, basicPeerConfigurationPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 762, Short.MAX_VALUE))
                .addContainerGap())
        );
        basicSettingsPanelLayout.setVerticalGroup(
            basicSettingsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(basicSettingsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(basicPeerConfigurationPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(discoveryServiceSettingsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 348, Short.MAX_VALUE)
                .addContainerGap())
        );

        tabs.addTab("Basic", basicSettingsPanel);

        tabs.addTab("Commune", communePanel);

        tabs.addTab("Failure Detection", fdPanel);
        
        tabs.addTab("Certification Authorities", cACertificatePanel);
        
        tabs.addTab("VOMS Authorization", vomsAuthPanel);
        
        advancedPeerSettingsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Advanced peer settings"));
        tabs.addTab("Advanced", advancedPeerSettingsPanel);
        
        tabs.addTab("Tags Configuration", tagsPeerConfigurationPanel);

        if (logSettingsPanel != null) {
        	logSettingsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Logging settings"));
        	logSettingsPanel.setPreferredSize(new java.awt.Dimension(200, 100));
        	tabs.addTab("Log", logSettingsPanel);
        }

        restoreDefaultsButton.setText("Restore defaults");
        restoreDefaultsButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				restoreButtonActionPerformed(e);
			}
        	
        });
        
        saveButton.setText("Save");
        saveButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				saveButtonActionPerformed(e);
			}
        	
        });
        
        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(saveButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(restoreDefaultsButton)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, tabs, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 794, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(tabs)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(restoreDefaultsButton)
                    .add(saveButton))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.ourgrid.peer.ui.async.gui.AdvancedPeerSettingsPanel advancedPeerSettingsPanel;
    private org.ourgrid.peer.ui.async.gui.BasicPeerConfigurationPanel basicPeerConfigurationPanel;
    private javax.swing.JPanel basicSettingsPanel;
    private CommuneSettingsPanel communePanel;
    private org.ourgrid.common.ui.gui.LogSettingsPanel logSettingsPanel;
    private org.ourgrid.peer.ui.async.gui.DiscoveryServiceSettingsPanel discoveryServiceSettingsPanel;
    private javax.swing.JButton restoreDefaultsButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JTabbedPane tabs;
    // End of variables declaration//GEN-END:variables

    /**
     * Disable the editable components of the internal panels.
     */
    public void disableFieldEdition() {
		advancedPeerSettingsPanel.disableFieldEdition();
		basicPeerConfigurationPanel.disableFieldEdition();
		communePanel.disableInput();
		fdPanel.disableInput();
		cACertificatePanel.disableInput();
		
		discoveryServiceSettingsPanel.disableFieldEdition();
		saveButton.setEnabled(false);
		restoreDefaultsButton.setEnabled(false);
	}
    
    /**
     * Enable the editable components of the internal panels.
     */
    public void enableFieldEdition() {
		advancedPeerSettingsPanel.enableFieldEdition();
		basicPeerConfigurationPanel.enableFieldEdition();
		communePanel.enableInput();
		fdPanel.enableInput();
		cACertificatePanel.enableInput();
		
		discoveryServiceSettingsPanel.enableFieldEdition();
		saveButton.setEnabled(true);
		restoreDefaultsButton.setEnabled(true);
	}
    
	/**
	 * Save the inputs of the internal panels.
	 */
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    		saveFieldInputs();
    	} catch (IOException e) {
    		//TODO - What should be done here?
    	}
    }
    
    private void restoreButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	try {
    		PeerAsyncInitializer.getInstance().getComponentClient().restoreDefaultPropertiesValues();
    		this.initFields();
    	} catch (IOException e) {
    		//TODO - What should be done here?
    	}
    }

    /**
     * Save the current properties of the PeerAsyncComponentClient.
     * @see PeerAsyncUIModel.saveProperties
     */
	private void saveProperties() {
		try {
			PeerAsyncInitializer.getInstance().getComponentClient().saveProperties();
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), 
					"IO Error" , JOptionPane.ERROR_MESSAGE);
		} finally {
			model.loadProperties();
		}
	}

	/**
	 * Initializes the textFields of the internal panels.
	 */
	public void initFields() throws IOException {
		basicPeerConfigurationPanel.initFields();
		discoveryServiceSettingsPanel.initFields();
		communePanel.initFields();
		fdPanel.initFields();
		cACertificatePanel.initFields();
		vomsAuthPanel.initFields();
		advancedPeerSettingsPanel.initFields();
		if (logSettingsPanel != null) {
			logSettingsPanel.initFields();
		}
	}

	/**
	 * Save the values of the internal panels field inputs.
	 */
	public void saveFieldInputs() throws IOException {
		basicPeerConfigurationPanel.saveProperties();
		discoveryServiceSettingsPanel.saveProperties();
		communePanel.saveFieldInputs();
		fdPanel.saveFieldInputs();
		cACertificatePanel.saveFieldInputs();
		vomsAuthPanel.saveFieldInputs();
		advancedPeerSettingsPanel.saveProperties();
		if (logSettingsPanel != null) {
			logSettingsPanel.saveProperties();
		}
		tagsPeerConfigurationPanel.saveProperties();
    	saveProperties();
	}

    /**
     * Disable the editable components of the internal panels.
     */
	public void disableInput() {
		disableFieldEdition();
		
	}

    /**
     * Enable the editable components of the internal panels.
     */
	public void enableInput() {
		enableFieldEdition();
		
	}
    
}
